//
//  MMNetworkingManager.m
//  MessageManagement
//
//  Created by 奚春竹 on 17/3/24.
//  Copyright © 2017年 奚春竹. All rights reserved.
//

#import "MMNetworkingManager.h"
#import "AFNetworking.h"
//#import "ATLoginViewController.h"
#import "PMAccount.h"

//#define baseUrl @"http://api.yuepinyouxuan.com/Home/Index?method="

@implementation MMNetworkingManager

+ (void)GET:(NSString *)urlString
     params:(id )parameters
    success:(SuccessBlock)successBlock
    failure:(FailureBlock)failureBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    /**
     *  可以接受的类型
     */
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    /**
     *  请求队列的最大并发数
     */
    manager.operationQueue.maxConcurrentOperationCount = 5;
    /**
     *  请求超时的时间
     */
    manager.requestSerializer.timeoutInterval = 60;
    
    
    //token
    NSString *url;
    PMAccount *account=[PMAccountTool account];
    if (account!=NULL) {
        url=[NSString stringWithFormat:@"%@%@?token=%@&tokenId=%lu",baseUrl,urlString,account.token,account.userId];
        NSLog(@"url====%@",url);
    }else{
        url=[NSString stringWithFormat:@"%@%@",baseUrl,urlString];
    }
    
    if ([url containsString:@"https://api.weixin.qq.com"]) {
        url = urlString;
    }
    
    [manager GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
        if (successBlock) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            //
            NSLog(@"%@",dic);
            if ([dic objectForKey:@"code"]!=[NSNull null]) {
                NSInteger code=[dic[@"code"] integerValue];
                if (code==3) {
                    [PMAccountTool saveAccount:nil];
//                    ATLoginViewController *vc = [[ATLoginViewController alloc] init];
//                    [UIApplication sharedApplication].keyWindow.rootViewController = vc;
                    //[YJProgressHUD showMessage:@"您的账号在别处登录，请确认密码是否泄漏"];
                }
            }
            successBlock(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //账户token失效
        NSString *desc = error.userInfo[@"NSLocalizedDescription"];
        if ([desc containsString:@"401"]) {
            [PMAccountTool saveAccount:nil];
//            ATLoginViewController *vc = [[ATLoginViewController alloc] init];
//            [UIApplication sharedApplication].keyWindow.rootViewController = vc;
//            [YJProgressHUD showMessage:@"账号验证失效，请重新登录"];
            return ;
        }
        //请求失败
        if (failureBlock) {
            failureBlock(error);
            NSLog(@"网络异常 - T_T%@", error);
        }
    }];
}


/**
 POST请求
 
 @param urlString url
 @param params 参数
 @param successBlock 成功的回调
 @param failureBlock 失败的回调
 */
+ (void)POST:(NSString *)urlString
      params:(id )params
     success:(SuccessBlock)successBlock
     failure:(FailureBlock)failureBlock{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 60;
    
    
    //token
    NSString *url;
    PMAccount *account=[PMAccountTool account];
    if (account!=NULL) {
        url=[NSString stringWithFormat:@"%@%@?token=%@&tokenId=%lu",baseUrl,urlString,account.token,account.userId];
        NSLog(@"url====%@",url);
    }else{
        url=[NSString stringWithFormat:@"%@%@",baseUrl,urlString];
    }
    
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            successBlock(responseObject);
//         if ([responseObject objectForKey:@"code"]!=[NSNull null]) {
//            NSInteger code=[responseObject[@"code"] integerValue];
//            if (code==3) {
//                [PMAccountTool saveAccount:nil];
//                PMLoginViewController *vc = [[PMLoginViewController alloc] init];
//                [UIApplication sharedApplication].keyWindow.rootViewController = vc;
//                [YJProgressHUD showMessage:@"您的账号在别处登录，请确认密码是否泄漏"];
//            }
//         }
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(error);
            NSLog(@"网络错误:\n%@",error);
            NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
            NSLog(@"错误信息:\n%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }
    }];
}
/**
 POST请求
 
 @param urlString url
 @param json json数据
 @param successBlock 成功的回调
 @param failureBlock 失败的回调
 */
+ (void)POST:(NSString *)urlString
        json:(id )json
     success:(SuccessBlock)successBlock
     failure:(FailureBlock)failureBlock{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 60;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", @"image/jpeg", nil];
    
    //token
    NSString *url;
    PMAccount *account=[PMAccountTool account];
    if (account!= NULL) {
        url=[NSString stringWithFormat:@"%@/%@?token=%@&tokenId=%lu",baseUrl,urlString,account.token,account.userId];
        NSLog(@"url====%@",url);
    }else{
        url=[NSString stringWithFormat:@"%@%@",baseUrl,urlString];
    }
    //
    [manager POST:url parameters:json progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            successBlock(responseObject);
//            if ([responseObject objectForKey:@"code"]!=[NSNull null]) {
//                NSInteger code=[responseObject[@"code"] integerValue];
//                if (code==3) {
//                    [PMAccountTool saveAccount:nil];
//                    PMLoginViewController *vc = [[PMLoginViewController alloc] init];
//                    [UIApplication sharedApplication].keyWindow.rootViewController = vc;
//                    [YJProgressHUD showMessage:@"您的账号在别处登录，请确认密码是否泄漏"];
//                }
//            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(error);
            NSLog(@"网络异常 - T_T%@", error);
            
            NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
            NSLog(@"错误信息:\n%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }
    }];
    
}
+ (void)DELETE:(NSString *)urlString
        params:(id )params
       success:(SuccessBlock)successBlock
       failure:(FailureBlock)failureBlock{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 60;
    
    //token
    NSString *url;
    PMAccount *account=[PMAccountTool account];
    if (account!=NULL) {
        url=[NSString stringWithFormat:@"%@/%@?token=%@&tokenId=%lu",baseUrl,urlString,account.token,account.userId];
        NSLog(@"url====%@",url);
    }else{
        url=[NSString stringWithFormat:@"%@/%@",baseUrl,urlString];
    }
    //
    [manager DELETE:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        if (successBlock) {
//            successBlock(responseObject);
//            NSInteger code=[responseObject[@"code"] integerValue];
//            if (code==3) {
//                [PMAccountTool saveAccount:nil];
//                PMLoginViewController *vc = [[PMLoginViewController alloc] init];
//                [UIApplication sharedApplication].keyWindow.rootViewController = vc;
//                [YJProgressHUD showMessage:@"您的账号在别处登录，请确认密码是否泄漏"];
//            }
//        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(error);
            NSLog(@"网络异常 - T_T%@", error);
            NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
            NSLog(@"错误信息:\n%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }
    }];
}
+(void)POSTImage:(NSString *)urlString
          params:(NSDictionary *)params
      imagesName:(NSString *)name
      imageArray:(NSArray *)imageArray
         success:(SuccessBlock)successBlock
         failure:(FailureBlock)failureBlock{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];//初始化请求对象
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];


    manager.requestSerializer.timeoutInterval = 60;

    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];


    NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
    [mutableHeaders setValue:@"form-data; name=\"distributionRoom\"" forKey:@"Content-Disposition"];
    [mutableHeaders setValue:@"text/html; charset=UTF-8" forKey:@"Content-Type"];

    //NSString *url = [NSString stringWithFormat:@"%@/%@",baseUrl,urlString];
    
    //token
    NSString *url;
    PMAccount *account=[PMAccountTool account];
    if (account!=NULL) {
        url=[NSString stringWithFormat:@"%@%@?token=%@&tokenId=%lu",baseUrl,urlString,account.token,account.userId];
        NSLog(@"url====%@",url);
    }else{
        url=[NSString stringWithFormat:@"%@%@",baseUrl,urlString];
    }

//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
//    hud.mode = MBProgressHUDModeAnnularDeterminate;
//    hud.label.text = @"正在上传数据";
//
//    hud.bezelView.backgroundColor = [UIColor blackColor];
//    [hud setMargin:10];
//    [hud setRemoveFromSuperViewOnHide:YES];
//    hud.contentColor = [UIColor whiteColor];


    [manager POST:url parameters:params constructingBodyWithBlock:^(id  _Nonnull formData) {

        if (!kArrayIsEmpty(imageArray)) {
            for (int i = 0; i < imageArray.count; i++) {
                //对于图片进行压缩

                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmmss";
                NSString *str = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString stringWithFormat:@"%@%d.jpg", str, i];
                
                NSData *data = UIImagePNGRepresentation(imageArray[i]);
                //第一个代表文件转换后data数据，第二个代表图片的名字，第三个代表图片放入文件夹的名字，第四个代表文件的类型
                [formData appendPartWithFileData:data name:fileName fileName:name mimeType:@"image/jpg"];
            }
        }

    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //hud.progressObject = uploadProgress;
        NSLog(@"上传进度:%.2f%%",100.0 * uploadProgress.completedUnitCount/uploadProgress.totalUnitCount);

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable object) {

        //[hud hideAnimated:YES];
        if (successBlock) {
            successBlock(object);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //[hud hideAnimated:YES];
        if (failureBlock) {
            failureBlock(error);

            NSLog(@"Error - T_T%@", error.userInfo);

            NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
            NSLog(@"错误信息:\n%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }
    }];
}

+(void)POSTListAndImage:(NSString *)urlString
          params:(NSDictionary *)params
      imagesName:(NSString *)name
      imageArray:(NSArray *)imageArray
         success:(SuccessBlock)successBlock
         failure:(FailureBlock)failureBlock{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];//初始化请求对象
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    
    manager.requestSerializer.timeoutInterval = 60;
    
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", @"image/jpeg", nil];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                        @"text/html",
                                                        @"image/jpeg",
                                                        @"image/png",
                                                        @"application/octet-stream",
                                                        @"text/json",
                                                        nil];
    
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
//    hud.mode = MBProgressHUDModeAnnularDeterminate;
//    hud.label.text = @"正在上传数据";
//
//    hud.bezelView.backgroundColor = [UIColor blackColor];
//    [hud setMargin:10];
//    [hud setRemoveFromSuperViewOnHide:YES];
//    hud.contentColor = [UIColor whiteColor];
//
    
   // NSString *url = [NSString stringWithFormat:@"%@/%@",baseUrl,urlString];
    //token
    NSString *url;
    PMAccount *account=[PMAccountTool account];
    if (account!=NULL) {
        url=[NSString stringWithFormat:@"%@/%@?token=%@&tokenId=%lu",baseUrl,urlString,account.token,account.userId];
        NSLog(@"url====%@",url);
    }else{
        url=[NSString stringWithFormat:@"%@%@",baseUrl,urlString];
    }
    
    [manager POST:url parameters:params constructingBodyWithBlock:^(id  _Nonnull formData) {
        
        
        
//        for (NSString *key in params) {
//            NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
//
//            [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"",key] forKey:@"Content-Disposition"];
//            [mutableHeaders setValue:@"application/json; charset=UTF-8" forKey:@"Content-Type"];
//            [mutableHeaders setValue:@"binary" forKey:@"Content-Transfer-Encoding"];
//
//
//            if ([params[key] isKindOfClass:[NSString class]]) {
//                [formData appendPartWithHeaders:mutableHeaders body:[params[key] dataUsingEncoding: NSUTF8StringEncoding]];
//            }else if ([params[key] isKindOfClass:[NSDictionary class]]){
//
//                [formData appendPartWithHeaders:mutableHeaders body:[params[key] yy_modelToJSONData]];
//
//            }else{
//                NSData *dataOnObject = [NSKeyedArchiver archivedDataWithRootObject:params[key]];
//                [formData appendPartWithHeaders:mutableHeaders body:dataOnObject];
//            }
//
//
            if (!kArrayIsEmpty(imageArray)) {
                for (int i = 0; i < imageArray.count; i++) {
                    //对于图片进行压缩
                    
                    NSData *data = UIImagePNGRepresentation(imageArray[i]);
                    //第一个代表文件转换后data数据，第二个代表图片的名字，第三个代表图片放入文件夹的名字，第四个代表文件的类型
                    [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"pic%02d.jpg",i] fileName:@"file" mimeType:@"image/jpg"];
                }
            }
//        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
       // hud.progressObject = uploadProgress;
        NSLog(@"上传进度:%.2f%%",100.0 * uploadProgress.completedUnitCount/uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable object) {
       // [hud hideAnimated:YES];
        NSLog(@"");
        if (successBlock) {
            successBlock(object);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //[hud hideAnimated:YES];
        if (failureBlock) {
            failureBlock(error);
            
            NSLog(@"Error - T_T%@", error.userInfo);
            
            NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
            NSLog(@"错误信息:\n%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }
    }];
}

@end


